package com.lightkits.wms.domain.deliveryorder.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.db.entity.FndEventTypeBase;
import com.lightkits.common.db.entity.event.BdEvent;
import com.lightkits.common.db.entity.event.BdEventRecord;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.framework.soa.client.id.IDServiceClient;
import com.lightkits.framework.soa.client.id.GetGlobalIDRequestType;
import com.lightkits.framework.soa.client.id.GetGlobalIDResponseType;
import com.lightkits.wms.domain.deliveryorder.model.EventParams;
import com.lightkits.wms.domain.deliveryorder.service.CreateDeliveryEventDomain;
import com.lightkits.wms.domain.saveonhand.SaveOnhandExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * CreateEventDomainImpl
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/2/26 19:30
 */
@Service
public class CreateDeliveryEventDomainImpl implements CreateDeliveryEventDomain {

    private final IDServiceClient idAdapterService;

    private static final Logger LOGGER = LoggerFactory.getLogger(SaveOnhandExecutor.class);

    @Autowired
    public CreateDeliveryEventDomainImpl(IDServiceClient idAdapterService) {
        this.idAdapterService = idAdapterService;
    }

    /**
     * 创建事件
     *
     * @param params 事件创建参数
     * @return
     */
    @Override
    public CheckResult<BdEvent> createEvent(EventParams params) {
        CheckResult<BdEvent> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        GetGlobalIDRequestType idRequest = new GetGlobalIDRequestType();
        idRequest.setCount(1);
        GetGlobalIDResponseType idResponse = idAdapterService.getGlobalId(idRequest);
        Iterator<Long> sfIds = idResponse.getIds().iterator();
        BdEvent event = new BdEvent();
        try {
            FndEventTypeBase eventTypeBase = new FndEventTypeBase()
                    .selectOne(new EntityWrapper<FndEventTypeBase>()
                            .eq(FndEventTypeBase.EVENT_TYPE_CODE, params.getEventTypeCode()));

            event.setEventTypeId(eventTypeBase.getId());
            event.setEventTypeCode(eventTypeBase.getEventTypeCode());
            event.setEventRequestId(sfIds.next());
            if (!ObjectUtil.isNullOrEmpty(params.getWorkerId())) {
                event.setWorkerId(ParseUtil.tryLongWithException(params.getWorkerId()));
            }
            if (!ObjectUtil.isNullOrEmpty(params.getOrgId())) {
                event.setOrganizationId(ParseUtil.tryLongWithException(params.getOrgId()));

            }
            if (!ObjectUtil.isNullOrEmpty(params.getParentEventId())) {
                event.setParentEventId(ParseUtil.tryLongWithException(params.getParentEventId()));
            }
            event.setCalendarDay(new Date());

            //create eventRecord
            List<BdEventRecord> records = new ArrayList<>();
            BdEventRecord eventRecord = createEventRecord(params.getObjectType(), params.getKeyValue(), params.getObjectId(), params.getRecordType());
            records.add(eventRecord);
            event.store(records);
        } catch (Exception e) {
            LOGGER.error("createEvent.error", e);
            throw new LightKitsBizException(e);
        }
        checkResult.setData(event);
        return checkResult;
    }

    /**
     * 事件快照的创建
     *
     * @param objectType 事件对象类型
     * @param keyValue   事件关键值
     * @param objectId   事件对象ID
     * @param recordType 事件记录类型
     * @return
     **/
    private BdEventRecord createEventRecord(String objectType, String keyValue, Long objectId, String recordType) {

        BdEventRecord eventRecord = new BdEventRecord();
        try {
            eventRecord.setObjectId(objectId);
            eventRecord.setObjectType(objectType);
            eventRecord.setRecordType(recordType);
            eventRecord.setKeyValue(keyValue);
        } catch (Exception e) {
            LOGGER.error("createEventRecord.error", e);
            throw new LightKitsBizException(e);
        }
        return eventRecord;
    }

}
